package com.webdemo01.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.webdemo01.javabean.User;
import com.webdemo01.util.DBHandler;

/**
 * Servlet implementation class UpdateUser
 */
public class UpdateUser extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UpdateUser() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String flag = request.getParameter("flag");
		if("show".equals(flag)){
			String id = request.getParameter("id");
			String sql = "select id,name from servlet03_user where id = ?";
			Connection conn = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			conn = DBHandler.newInstance().getConnection();
			User user = null;
			try {
				pstmt = conn.prepareStatement(sql);
				pstmt.setInt(1, Integer.parseInt(id));
				rs = pstmt.executeQuery();
				if(rs.next()){
					id = rs.getString("id");
					String name = rs.getString("name");
					user = new User();
					user.setId(Integer.parseInt(id));
					user.setName(name);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.setAttribute("user", user);
			request.getRequestDispatcher("/WEB-INF/jsp/update.jsp").forward(request, response);
		}else if("update".equals(flag)){
			String id = request.getParameter("id");
			String name = request.getParameter("name");
			String sql = "update servlet03_user set name=? where id=?";
			Connection conn = null;
			PreparedStatement pstmt = null;
			conn = DBHandler.newInstance().getConnection();
			try {
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, name);
				pstmt.setString(2, id);
				pstmt.executeUpdate();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			response.sendRedirect(this.getServletContext().getContextPath()+"/QueryUser");
		}
		
	}

}
